export default {
    data() {
        return {
            deviceType: '',
            deviceTitle: '',
            deviceUnit: '',
            todayValue: '0.00',
            monthValue: '0.00',
            dailyChartData: {
                categories: [],
                series: [{
                    name: '数据',
                    data: [],
                }],
            },
            monthlyChartData: {
                categories: [],
                series: [{
                    name: '数据',
                    data: [],
                }],
            },
            dailyDataTooltip: {
                show: false,
                x: 0,
                y: 0,
                time: '',
                value: ''
            },
            monthlyDataTooltip: {
                show: false,
                x: 0,
                y: 0,
                time: '',
                value: ''
            },
            dailyChartInfo: {
                padding: 40,
                width: 0,
                height: 0,
                chartWidth: 0,
                chartHeight: 0,
                maxValue: 0,
                minValue: 0,
                pointsCoordinate: []
            },
            monthlyChartInfo: {
                padding: 40,
                width: 0,
                height: 0,
                chartWidth: 0,
                chartHeight: 0,
                maxValue: 0,
                minValue: 0,
                pointsCoordinate: []
            }
        };
    },
    onLoad(options) {
        // 从路由参数获取设备类型
        console.log('Received type:', options.type); // 确认接收到tempHumidity
        this.deviceType = options.type || '';
        console.log('Current deviceType:', this.deviceType); // 确认赋值成功
        this.initDeviceConfig();
        this.generateMockData();
    },
    onReady() {
        this.drawChartWithAnimation('daily');
        this.drawChartWithAnimation('monthly');
    },
    methods: {
        // 根据不同设备类型初始化配置
        initDeviceConfig() {
            switch (this.deviceType) {
                case 'tempHumidity':
                    this.deviceTitle = '温湿度';
                    this.deviceUnit = '°C/%';
                    break;
                case '光照强度':
                    this.deviceTitle = '光照强度';
                    this.deviceUnit = 'lux';
                    break;
                case '烟雾浓度':
                    this.deviceTitle = '烟雾浓度';
                    this.deviceUnit = 'mg/m³';
                    break;
                case '空气质量':
                    this.deviceTitle = '空气质量';
                    this.deviceUnit = 'mg/m³';
                    break;
                // 可以添加更多设备类型的配置
                default:
                    this.deviceTitle = '设备数据';
                    this.deviceUnit = '';
            }
        },
        // 生成模拟数据
        generateMockData() {
            // 24小时数据
            const hours = Array.from({length: 24}, (_, i) => `${i.toString().padStart(2, '0')}:00`);
            const dailyData = hours.map((_, index) => {
                if (this.deviceType === 'tempHumidity') {
                    return +(Math.random() * 10 + 20).toFixed(1); // 温度模拟
                }
                return +(Math.random() * 50 + 10).toFixed(1);
            });

            this.dailyChartData.categories = hours;
            this.dailyChartData.series[0].data = dailyData;
            this.todayValue = dailyData.reduce((sum, val) => sum + val, 0).toFixed(2);

            // 月度数据
            const days = Array.from({length: 30}, (_, i) => `${i + 1}日`);
            const monthlyData = days.map(() => +(Math.random() * 50 + 10).toFixed(1));

            this.monthlyChartData.categories = days;
            this.monthlyChartData.series[0].data = monthlyData;
            this.monthValue = monthlyData.reduce((sum, val) => sum + val, 0).toFixed(2);
        },
        // 图表触摸和交互方法
        // 以下方法与 power.vue 页面的实现类似，可以直接复用
        onChartTouch(type, event) {
            // 实现与 power.vue 相同的触摸事件处理逻辑
        },
        onChartTouchEnd() {
            this.dailyDataTooltip.show = false;
            this.monthlyDataTooltip.show = false;
        },
        findNearestPoint(touchX, touchY, chartInfo) {
            // 实现与 power.vue 相同的最近点查找逻辑
        },
        drawChartWithAnimation(type) {
            const canvasId = type === 'daily' ? '#dailyDeviceChart' : '#monthlyDeviceChart';
            const query = wx.createSelectorQuery();
            query.select(canvasId)
                .fields({node: true, size: true})
                .exec((res) => this.renderChartAnimation(res, type));
        },
        renderChartAnimation(res, type) {
            const canvas = res[0].node;
            const ctx = canvas.getContext('2d');

            // 获取设备像素比并设置画布大小
            const dpr = wx.getSystemInfoSync().pixelRatio;
            canvas.width = res[0].width * dpr;
            canvas.height = res[0].height * dpr;
            ctx.scale(dpr, dpr);

            const chartData = type === 'daily' ? this.dailyChartData : this.monthlyChartData;
            const data = chartData.series[0].data;
            const categories = chartData.categories;
            const width = res[0].width;
            const height = res[0].height;

            const padding = 40;
            const chartWidth = width - 2 * padding;
            const chartHeight = height - 2 * padding;

            // 保存图表信息
            const chartInfo = {
                padding,
                width,
                height,
                chartWidth,
                chartHeight,
                maxValue: Math.max(...data),
                minValue: Math.min(...data),
                pointsCoordinate: []
            };

            if (type === 'daily') {
                this.dailyChartInfo = chartInfo;
            } else {
                this.monthlyChartInfo = chartInfo;
            }

            const maxValue = chartInfo.maxValue;
            const minValue = chartInfo.minValue;

            // 创建渐变背景
            const gradient = ctx.createLinearGradient(0, 0, 0, height);
            gradient.addColorStop(0, 'rgba(57, 117, 212, 0.1)');
            gradient.addColorStop(1, 'rgba(57, 117, 212, 0.02)');

            // 动画函数
            const animate = (progress) => {
                // 清空画布并设置背景
                ctx.clearRect(0, 0, width, height);
                ctx.fillStyle = '#f9fbff';
                ctx.fillRect(0, 0, width, height);

                // 绘制网格线
                ctx.strokeStyle = '#e6f1ff';
                ctx.lineWidth = 1;
                const gridLines = 5;
                for (let i = 0; i <= gridLines; i++) {
                    const y = padding + (chartHeight * i) / gridLines;
                    ctx.beginPath();
                    ctx.moveTo(padding, y);
                    ctx.lineTo(width - padding, y);
                    ctx.stroke();
                }

                // 绘制坐标轴
                ctx.strokeStyle = '#d1e6ff';
                ctx.lineWidth = 2;

                // X轴
                ctx.beginPath();
                ctx.moveTo(padding, height - padding);
                ctx.lineTo(width - padding, height - padding);
                ctx.stroke();

                // Y轴
                ctx.beginPath();
                ctx.moveTo(padding, padding);
                ctx.lineTo(padding, height - padding);
                ctx.stroke();

                // 绘制折线
                ctx.beginPath();
                ctx.strokeStyle = '#3975d4';
                ctx.lineWidth = 3;

                // 创建阴影效果
                ctx.shadowColor = 'rgba(57, 117, 212, 0.3)';
                ctx.shadowBlur = 10;

                const animatedData = data.slice(0, Math.ceil(data.length * progress));
                const pointsCoordinate = [];

                animatedData.forEach((value, index) => {
                    const x = padding + (chartWidth * index) / (data.length - 1);
                    const y = height - padding -
                        ((value - minValue) / (maxValue - minValue)) * chartHeight;

                    pointsCoordinate.push({x, y});

                    if (index === 0) {
                        ctx.moveTo(x, y);
                    } else {
                        ctx.lineTo(x, y);
                    }
                });

                ctx.stroke();

                // 关闭阴影
                ctx.shadowBlur = 0;

                // 填充渐变背景
                if (progress === 1) {
                    ctx.beginPath();
                    pointsCoordinate.forEach((point, index) => {
                        if (index === 0) {
                            ctx.moveTo(point.x, point.y);
                        } else {
                            ctx.lineTo(point.x, point.y);
                        }
                    });

                    ctx.lineTo(width - padding, height - padding);
                    ctx.lineTo(padding, height - padding);
                    ctx.closePath();

                    ctx.fillStyle = gradient;
                    ctx.fill();

                    // 更新点坐标数组
                    if (type === 'daily') {
                        this.dailyChartInfo.pointsCoordinate = pointsCoordinate;
                    } else {
                        this.monthlyChartInfo.pointsCoordinate = pointsCoordinate;
                    }

                    // 绘制数据点
                    ctx.fillStyle = '#3975d4';
                    pointsCoordinate.forEach((point) => {
                        ctx.beginPath();
                        ctx.arc(point.x, point.y, 4, 0, 2 * Math.PI);
                        ctx.fill();
                    });

                    // 绘制X轴标签
                    ctx.fillStyle = '#8b9cb3';
                    ctx.font = '10px Arial';
                    ctx.textAlign = 'center';
                    data.forEach((_, index) => {
                        if (index % Math.ceil(data.length / 6) === 0) {
                            const x = padding + (chartWidth * index) / (data.length - 1);
                            ctx.fillText(categories[index], x, height - 10);
                        }
                    });

                    // 绘制Y轴标签
                    ctx.textAlign = 'right';
                    [minValue, (minValue + maxValue) / 2, maxValue].forEach((value) => {
                        const y = height - padding -
                            ((value - minValue) / (maxValue - minValue)) * chartHeight;
                        ctx.fillText(value.toFixed(1), padding - 10, y + 4);
                    });
                }
            };

            // 动画控制
            const duration = 1800; // 稍微延长动画时间
            const startTime = Date.now();

            const step = () => {
                const currentTime = Date.now();
                const elapsed = currentTime - startTime;
                const progress = Math.min(elapsed / duration, 1);

                // 使用缓动函数使动画更自然
                const easedProgress = 1 - Math.pow(1 - progress, 4);

                animate(easedProgress);

                if (progress < 1) {
                    canvas.requestAnimationFrame(step);
                }
            };

            canvas.requestAnimationFrame(step);
        },
        goBack() {
            uni.navigateBack();
        }
    }
}